package com.zzk.www.tool.common;

import org.apache.commons.lang3.SystemUtils;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * Created by zzk on 2017/12/21.
 */
public class SystemUtil {

    public static String getIp() {
        return getSystemIP("eth1");
    }

    public static String getLocalIp() {
        return getSystemIP("eth0");
    }

    private static String getSystemIP(String netType) {
        try {
            if(!SystemUtils.IS_OS_WINDOWS && !SystemUtils.IS_OS_MAC && !SystemUtils.IS_OS_MAC_OSX) {
                Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();

                while(true) {
                    NetworkInterface ni;
                    String network;
                    do {
                        if(!netInterfaces.hasMoreElements()) {
                            return "01";
                        }

                        ni = (NetworkInterface)netInterfaces.nextElement();
                        network = ni.getName();
                    } while(!netType.equalsIgnoreCase(network));

                    Enumeration inetAddres = ni.getInetAddresses();

                    while(inetAddres.hasMoreElements()) {
                        InetAddress ip = (InetAddress)inetAddres.nextElement();
                        if(ip != null && ip instanceof Inet4Address) {
                            Inet4Address ipv4 = (Inet4Address)ip;
                            return ipv4.getHostAddress();
                        }

                        if(ip != null && ip instanceof Inet6Address) {
                            Inet6Address var5 = (Inet6Address)ip;
                        }
                    }
                }
            } else {
                return InetAddress.getLocalHost() == null?"":InetAddress.getLocalHost().getHostAddress().toString();
            }
        } catch (Exception var8) {
            return "00";
        }
    }
}
